#!/usr/bin/env node

/**
 * 批量导入模板数据脚本
 * 从 public/template.json 读取数据并通过 API 接口导入到数据库
 */

const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');

// API 基础配置
const API_BASE_URL = 'http://localhost:3008/api/templates-db';
const TEMPLATE_JSON_PATH = path.join(__dirname, '../public/template.json');

// 延迟函数，避免请求过于频繁
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 发送 DELETE 请求清空所有模板数据
function clearAllTemplates() {
  return new Promise((resolve) => {
    const options = {
      hostname: 'localhost',
      port: 3008,
      path: '/api/templates-db',
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 10000 // 10秒超时
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          
          if (result.success) {
            console.log(`🗑️  成功清空所有模板数据`);
            resolve({ success: true, data: result.data });
          } else {
            console.error(`❌ 清空模板数据失败: ${result.error}`);
            resolve({ success: false, error: result.error });
          }
        } catch (error) {
          console.error(`❌ 解析清空响应失败: ${error.message}`);
          resolve({ success: false, error: error.message });
        }
      });
    });

    req.on('error', (error) => {
      console.error(`❌ 清空请求失败: ${error.message}`);
      resolve({ success: false, error: error.message });
    });

    req.on('timeout', () => {
      console.error(`❌ 清空请求超时`);
      req.destroy();
      resolve({ success: false, error: '请求超时' });
    });

    req.end();
  });
}

// 发送 POST 请求创建模板
function createTemplate(templateData) {
  return new Promise((resolve) => {
    const postData = JSON.stringify({ template: templateData });
    
    const options = {
      hostname: 'localhost',
      port: 3008,
      path: '/api/templates-db',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      },
      timeout: 10000 // 10秒超时
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          
          if (result.success) {
            console.log(`✅ 成功创建模板: ${templateData.name} (${templateData.type})`);
            resolve({ success: true, data: result.data });
          } else {
            console.error(`❌ 创建模板失败: ${templateData.name} - ${result.error}`);
            if (result.details) {
              console.error(`📋 详细错误:`, result.details);
            }
            resolve({ success: false, error: result.error, details: result.details });
          }
        } catch (error) {
          console.error(`❌ 解析响应失败: ${templateData.name} - ${error.message}`);
          resolve({ success: false, error: error.message });
        }
      });
    });

    req.on('error', (error) => {
      console.error(`❌ 请求失败: ${templateData.name} - ${error.message}`);
      resolve({ success: false, error: error.message });
    });

    req.on('timeout', () => {
      console.error(`❌ 请求超时: ${templateData.name}`);
      req.destroy();
      resolve({ success: false, error: '请求超时' });
    });

    req.write(postData);
    req.end();
  });
}

// 转换模板数据格式
function transformTemplateData(template, type) {
  const baseData = {
    id: template.id,
    name: template.name,
    description: template.description,
    type: type,
    image: template.image,
    base_model: template.base_model,
    lora_model: template.lora_model || '',
    lora_output_name: template.lora_output_name || '',
    lora_weight: template.lora_weight || 0.8,
    vae: template.vae || '',
    prompt: template.prompt || '',
    negative_prompt: template.negative_prompt || '',
    sampler_name: template.sampler_name || 'DPM++ 2M Karras',
    steps: template.steps || 20,
    cfg_scale: template.cfg_scale || 7.0,
    width: template.width || 1024,
    height: template.height || 1024,
    seed: template.seed || -1,
    batch_count: template.batch_count || 1,
    batch_size: template.batch_size || 1
  };

  // 根据类型添加特有字段
  if (type === 'img2img') {
    baseData.denoising_strength = template.denoising_strength || 0.75;
  } else if (type === 'postprocess') {
    // postprocess类型的必需字段
    baseData.resize_mode = template.resize_mode !== undefined ? template.resize_mode : 0;
    baseData.upscaling_resize = template.upscaling_resize || 2;
    baseData.upscaling_resize_w = template.upscaling_resize_w || 512;
    baseData.upscaling_resize_h = template.upscaling_resize_h || 512;
    baseData.upscaling_crop = template.upscaling_crop !== undefined ? template.upscaling_crop : false;
    baseData.upscaler_1 = template.upscaler_1 || 'R-ESRGAN 4x+';
    baseData.upscaler_2 = template.upscaler_2 || 'None';
    baseData.extras_upscaler_2_visibility = template.extras_upscaler_2_visibility !== undefined ? template.extras_upscaler_2_visibility : 0;
    
    // 移除postprocess类型不需要的字段
    delete baseData.base_model;
    delete baseData.lora_model;
    delete baseData.lora_output_name;
    delete baseData.lora_weight;
    delete baseData.vae;
    delete baseData.prompt;
    delete baseData.negative_prompt;
    delete baseData.sampler_name;
    delete baseData.steps;
    delete baseData.cfg_scale;
    delete baseData.width;
    delete baseData.height;
    delete baseData.seed;
    delete baseData.batch_count;
    delete baseData.batch_size;
  }

  return baseData;
}

// 主函数
async function main() {
  console.log('🚀 开始批量导入模板数据...');
  
  try {
    // 检查模板文件是否存在
    if (!fs.existsSync(TEMPLATE_JSON_PATH)) {
      console.error(`❌ 模板文件不存在: ${TEMPLATE_JSON_PATH}`);
      process.exit(1);
    }

    // 读取模板数据
    const templateData = JSON.parse(fs.readFileSync(TEMPLATE_JSON_PATH, 'utf8'));
    console.log(`📖 成功读取模板文件: ${TEMPLATE_JSON_PATH}`);

    // 清空现有的模板数据
    console.log('\n🗑️  正在清空现有模板数据...');
    const clearResult = await clearAllTemplates();
    if (!clearResult.success) {
      console.error(`❌ 清空数据失败: ${clearResult.error}`);
      console.log('⚠️  继续导入新数据...');
    }

    let totalCount = 0;
    let successCount = 0;
    let failureCount = 0;
    const failures = [];

    // 处理 txt2img 模板
    if (templateData.txt2img && Array.isArray(templateData.txt2img)) {
      console.log(`\n📝 开始导入 ${templateData.txt2img.length} 个 txt2img 模板...`);
      for (const template of templateData.txt2img) {
        const transformedData = transformTemplateData(template, 'txt2img');
        const result = await createTemplate(transformedData);
        
        totalCount++;
        if (result.success) {
          successCount++;
        } else {
          failureCount++;
          failures.push({ name: template.name, type: 'txt2img', error: result.error });
        }
        
        // 延迟避免请求过于频繁
        await delay(100);
      }
    }

    // 处理 img2img 模板
    if (templateData.img2img && Array.isArray(templateData.img2img)) {
      console.log(`\n🖼️  开始导入 ${templateData.img2img.length} 个 img2img 模板...`);
      for (const template of templateData.img2img) {
        const transformedData = transformTemplateData(template, 'img2img');
        const result = await createTemplate(transformedData);
        
        totalCount++;
        if (result.success) {
          successCount++;
        } else {
          failureCount++;
          failures.push({ name: template.name, type: 'img2img', error: result.error });
        }
        
        await delay(100);
      }
    }

    // 处理 postprocess 模板
    if (templateData.postprocess && Array.isArray(templateData.postprocess)) {
      console.log(`\n⚙️  开始导入 ${templateData.postprocess.length} 个 postprocess 模板...`);
      for (const template of templateData.postprocess) {
        const transformedData = transformTemplateData(template, 'postprocess');
        const result = await createTemplate(transformedData);
        
        totalCount++;
        if (result.success) {
          successCount++;
        } else {
          failureCount++;
          failures.push({ name: template.name, type: 'postprocess', error: result.error });
        }
        
        await delay(100);
      }
    }

    // 输出导入结果统计
    console.log('\n📊 导入结果统计:');
    console.log(`总计: ${totalCount} 个模板`);
    console.log(`成功: ${successCount} 个`);
    console.log(`失败: ${failureCount} 个`);
    
    if (failures.length > 0) {
      console.log('\n❌ 失败详情:');
      failures.forEach(failure => {
        console.log(`  - ${failure.name} (${failure.type}): ${failure.error}`);
      });
    }

    console.log('\n🎉 批量导入完成!');
    
  } catch (error) {
    console.error(`❌ 导入过程中发生错误: ${error.message}`);
    process.exit(1);
  }
}

// 检查是否直接运行此脚本
if (require.main === module) {
  main().catch(error => {
    console.error('❌ 脚本执行失败:', error);
    process.exit(1);
  });
}

module.exports = { main, createTemplate, transformTemplateData, clearAllTemplates };